﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SqlSugar_Bugs.Entities;
using System.Collections.Concurrent;

namespace SqlSugar_Bugs
{
    internal class WorkingService : BackgroundService
    {
        private readonly ILogger _logger;
        private readonly ReportRecordService _reportRecordService;
        private static double _timerRunning;
        private readonly System.Timers.Timer _processTimer = new();
        private readonly BlockingCollection<ReportRecordEntity> _executingTasks = [];

        public WorkingService(ILogger<WorkingService> logger, ReportRecordService reportRecordService)
        {
            _logger = logger;
            _reportRecordService = reportRecordService;
            _processTimer.Elapsed += ProcessTimer_Elapsed;
            _processTimer.Interval = 10000;

            Task.Factory.StartNew(async state => await ProcessQueue(), this, TaskCreationOptions.LongRunning);
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _processTimer.Enabled = true;

            return base.StartAsync(cancellationToken);
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            return Task.CompletedTask;
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            _processTimer.Enabled = false;
            return base.StopAsync(cancellationToken);
        }

        private async void ProcessTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.CompareExchange(ref _timerRunning, 1, 0) == 0)
            {
                try
                {
                    for (int i = 0; i < 10; i++)
                    {
                        var entity = await _reportRecordService.CreateNew();
                        _executingTasks.Add(entity);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"{this.GetType()}.{nameof(ProcessTimer_Elapsed)}");
                }
                finally
                {
                    Interlocked.Exchange(ref _timerRunning, 0);
                }
            }
        }

        private async Task ProcessQueue()
        {
            var rand = new Random();

            foreach (var entity in _executingTasks.GetConsumingEnumerable())
            {
                try
                {
                    var num = rand.Next(10, 30);
                    if (num > 20)
                    {
                        await _reportRecordService.UpdateSuccess(entity.Id);
                    }
                    else
                    {
                        await _reportRecordService.UpdateFailure(entity.Id, "乱七八糟的错误消息");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "报错啦");
                }
            }
        }
    }
}
